package com.hamaluik.TradeIn;

import java.util.logging.Logger;

import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import com.nijiko.permissions.PermissionHandler;
import com.nijikokun.bukkit.Permissions.Permissions;

public class TradeIn extends JavaPlugin {
	Logger log = Logger.getLogger("Minecraft");
	public PermissionHandler permissionHandler;
	
	// startup routine..
	public void onEnable() {
		// setup permissions
		setupPermissions();
		
		// register the /trade command
		this.getCommand("trade").setExecutor(new TradeInCommandExecutor(this));
		
		// log startup information
		log.info("[TradeIn] plugin enabled");
	}
	
	// shutdown routine
	public void onDisable() {
		// nothing really to do here yet..
		// log shutdown information
		log.info("[TradeIn] plugin disabled");
	}
	
	// allow for colour tags to be used in strings..
	public String processColours(String str) {
		// from:
		// http://www.minecraftwiki.net/wiki/Classic_Server_Protocol#Color_Codes
		str = str.replace("&0", ChatColor.BLACK.toString());
		str = str.replace("&1", ChatColor.DARK_BLUE.toString());
		str = str.replace("&2", ChatColor.DARK_GREEN.toString());
		str = str.replace("&3", ChatColor.DARK_AQUA.toString());
		str = str.replace("&4", ChatColor.DARK_RED.toString());
		str = str.replace("&5", ChatColor.DARK_PURPLE.toString());
		str = str.replace("&6", ChatColor.GOLD.toString());
		str = str.replace("&7", ChatColor.GRAY.toString());
		str = str.replace("&8", ChatColor.DARK_GRAY.toString());
		str = str.replace("&9", ChatColor.BLUE.toString());
		str = str.replace("&a", ChatColor.GREEN.toString());
		str = str.replace("&b", ChatColor.AQUA.toString());
		str = str.replace("&c", ChatColor.RED.toString());
		str = str.replace("&d", ChatColor.LIGHT_PURPLE.toString());
		str = str.replace("&e", ChatColor.YELLOW.toString());
		str = str.replace("&f", ChatColor.WHITE.toString());
		return str;
	}
	
	// just an interface function for checking permissions
	// if permissions are down, default to OP status.
	public boolean hasPermission(Player player, String permission) {
		if(permissionHandler == null) {
			return player.isOp();
		}
		else {
			return permissionHandler.has(player, permission);
		}
	}
	
	// load the permissions plugin..
	private void setupPermissions() {
		Plugin permissionsPlugin = this.getServer().getPluginManager().getPlugin("Permissions");
		
		if(this.permissionHandler == null) {
			if(permissionsPlugin != null) {
				this.permissionHandler = ((Permissions)permissionsPlugin).getHandler();
				log.info("[TradeIn] permissions successfully loaded");
			} else {
				log.info("[TradeIn] permission system not detected, defaulting to OP");
			}
		}
	}
}
